package com.smarttest.common.util.mqtt;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.msgpack.MessagePack;

import com.g7s.test.utils.common.CommonUtils;
import com.smarttest.common.util.mqtt.v2.Gpsmsg2;
import com.smarttest.common.util.mqtt.v2.GpsmsgList2;

//V2支持便携和固定式
public class MQTT_DSDZ_CTB{
		// 类型：0:便携式  1：固定式 
	private static final int ctb = 1;
	private static final int dsdz = 0;
//	private static int model = dsdz;
//	private static int sleeptime = 5000;
//	private static int code = 3130;//1060    3130
//	private static String simno = "00060039310";//00060039310      14002020068    14086666661    F08060B1D30
	private static final int qos = 1;
//	private static String topic = "httx/input/gpsmsg/v2/test";
	// 登录信息
//		private static String broker = "tcp://172.30.4.2:1883";//测试
//		private static String broker = "tcp://60.28.195.206:883";//线上
//	private static String broker = "tcp://172.16.18.10:1883";//aliyun  
//		private static String broker = "tcp://118.178.33.52:883";//aliyun  


	/**
	 * 发送mqtt报文
	 * @param url
	 * @param topic
	 * @param imei
	 * @param model 0:便携式  1：固定式 
	 * @param internal 间隔时间，单位:s
	 * @return
	 * @throws IOException
	 */
	public static Map<Integer, Date> sendmsg(String url,String topic,String imei,int model,int internal) throws IOException {
		Map<Integer,Date> m = new HashMap<Integer, Date>();
		int code = Integer.parseInt(imei.substring(0, 4));
		String deviceno = imei.substring(4, imei.length());
		int index = 1;
			 MemoryPersistence persistence = new MemoryPersistence();
			 try {			 
	            MqttAsyncClient sampleClient = new MqttAsyncClient(url, MqttAsyncClient.generateClientId(), persistence);
	            MqttConnectOptions connOpts = new MqttConnectOptions();
	            connOpts.setCleanSession(false);
	            System.out.println("Connecting to broker: " + url);
	            sampleClient.connect(connOpts);
	            if (model == ctb) {
					System.out.println("固定式冷链--：");
					 Gpsmsg2 loc = new Gpsmsg2();
					int count=1;
					@SuppressWarnings("resource")
					BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(CommonUtils.getFilePath("mqtt_ctb.txt"))));
							for (String line = br.readLine(); line != null; line = br.readLine()) {
								System.out.print("第"+count+"条MQTT_ctb: ");
								String[] aa=line.split("/");
								Date currentTime = new Date();
								SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
								String dateStringtime = formatter.format(currentTime);
								 loc.setType(1);                     //0:便携式,1:固定式
								 loc.setCmd("gpsmsg");               //命令码
								 loc.setCode(code);                  //厂商编码
								 loc.setMode(2);                     //模式:  1/车牌号    2/设备号或sim卡号
								 loc.setDeviceno(deviceno);             //设备号或sim卡号
								 loc.setTime(dateStringtime);              //定位时间
								 loc.setLat(Double.parseDouble(aa[8]));             //纬度
								 loc.setLng(Double.parseDouble(aa[9]));            //经度
								 loc.setSpeed(20);                   //速度
								 loc.setCourse(20);                  //方向
								 loc.getGpsStatus2().setGps(Integer.parseInt(aa[0]));       //status  gps  只有1才会入库   !请注意!
								 loc.getGpsStatus2().setAcc(Integer.parseInt(aa[1]));       //status  acc
								 loc.getGpsStatus2().setCompress(Integer.parseInt(aa[2]));  //status  compress
								 loc.getGpsStatus2().setDoor(Integer.parseInt(aa[3]));      //status  door
								 loc.getTemperature2().setT1(Double.parseDouble(aa[4]));    //温度
								 loc.getTemperature2().setT2(Double.parseDouble(aa[5]));  
								 loc.getTemperature2().setT3(Double.parseDouble(aa[6]));   
								 loc.getTemperature2().setT4(Double.parseDouble(aa[7]));   
								 loc.getTemperature2().setH1(10.55);   
//								 loc.getTemperature2().setH2(Double.parseDouble(aa[9]));   
//								 loc.getTemperature2().setH3(Double.parseDouble(aa[10]));   
//								 loc.getTemperature2().setH4(Double.parseDouble(aa[11])); 
								System.out.println(loc);
								count++;
					System.out.println(loc);
	                List<Gpsmsg2> gpsmsgList = new ArrayList<Gpsmsg2>();
	                gpsmsgList.add(loc);
	                GpsmsgList2 gl = new GpsmsgList2();
	                gl.setGpsmsgList(gpsmsgList);
	                MessagePack msgpack = new MessagePack();
	                byte[] raw = null;
	                raw = ZipUtils.gzip(msgpack.write(gl));
	                MqttMessage message = new MqttMessage(raw);
	                message.setQos(qos);
	                sampleClient.publish(topic, message);
	                m.put(index, currentTime);
	                index++;
					try {
						Thread.sleep(internal*1000);
					} catch (InterruptedException e) {
						System.out.println(e);
					}
      				}
				} else if (model == dsdz){
					System.out.println("便携定式冷链--：");
					Gpsmsg2 loc = new Gpsmsg2();
					int count=1;
					@SuppressWarnings("resource")
					BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(CommonUtils.getFilePath("mqtt_dsdz.txt"))));
							for (String line = br.readLine(); line != null; line = br.readLine()) {
								System.out.print("第"+count+"条MQTT_dsdz: ");
								String[] aa=line.split("/");
								Date currentTime = new Date();
								SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
								String dateStringtime = formatter.format(currentTime);
								 loc.setType(0);                     //0:便携式,1:固定式
								 loc.setCmd("gpsmsg");               //命令码
								 loc.setCode(code);                  //厂商编码
								 loc.setMode(2);                     //模式:  1/车牌号    2/设备号或sim卡号
								 loc.setDeviceno(deviceno);             //设备号或sim卡号
								 loc.setTime(dateStringtime);              //定位时间
								 loc.setLat(Double.parseDouble(aa[0]));             //纬度
								 loc.setLng(Double.parseDouble(aa[1]));            //经度
								 loc.setSpeed(20);                   //速度
								 loc.setCourse(20);                  //方向
								 loc.getGpsStatus2().setGps(Integer.parseInt(aa[2]));       //status  gps  只有1才会入库   !请注意!
								 loc.getGpsStatus2().setBp(Integer.parseInt(aa[3]));        //电量
								 loc.getTemperature2().setT1(Double.parseDouble(aa[4]));    //温度
								 loc.getTemperature2().setH1(Double.parseDouble(aa[5]));    //湿度
								System.out.println(loc);
								count++;
	                List<Gpsmsg2> gpsmsgList = new ArrayList<Gpsmsg2>();
	                gpsmsgList.add(loc);
	                GpsmsgList2 gl = new GpsmsgList2();
	                gl.setGpsmsgList(gpsmsgList);
	                MessagePack msgpack = new MessagePack();
	                byte[] raw = null;
	                raw = ZipUtils.gzip(msgpack.write(gl));
	                MqttMessage message = new MqttMessage(raw);
	                message.setQos(qos);
	                sampleClient.publish(topic, message);
	                m.put(index, currentTime);
	                index++;
					try {
						Thread.sleep(internal*1000);
					} catch (InterruptedException e) {
						System.out.println(e);
					}
			}
			 }
	            }
	            catch (MqttException me) {
		            System.out.println("reason " + me.getReasonCode());
		            System.out.println("msg " + me.getMessage());
		            System.out.println("loc " + me.getLocalizedMessage());
		            System.out.println("cause " + me.getCause());
		            System.out.println("excep " + me);
		            me.printStackTrace();
		        }
			 return m;
	}
}
